package top.cnspt.pdf.controllers;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.cnspt.pdf.utils.Pdf;
import top.cnspt.pdf.utils.Empty;
import top.cnspt.pdf.utils.JsonData;
import java.util.*;

@Controller
@RequestMapping("index")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class IndexController {
    @RequestMapping("index" )
    public String index() {
        return "index/index";
    }

    @Value("${pdf.path}")
    public String path;

    @Value("${pdf.newPath}")
    public String newPath;

    @ResponseBody
    @RequestMapping("gpdf")
    public JsonData gpdf(@RequestBody JSONObject jsonParam) {
        //获取前端post过来的json数据
        String pdfPath = jsonParam.get("pdfPath").toString();
        String newPDFPath = jsonParam.get("newPDFPath").toString();
        String pdfHeight = jsonParam.get("pdfHeight").toString();
        String pdfWidth = jsonParam.get("pdfWidth").toString();
        String pwd = jsonParam.get("pwd").toString();
        String seal = jsonParam.get("seal").toString();
        String jsonString = jsonParam.get("signs").toString();

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        JSONObject jsonObject = JSONObject.parseObject(jsonString);
//        LinkedHashMap signMap = (LinkedHashMap)jsonObject1;
        Iterator itSigns = jsonObject.entrySet().iterator();
        while (itSigns.hasNext()) {
            Map.Entry entrySigns = (Map.Entry) itSigns.next();
            JSONObject lhpSigns = (JSONObject)entrySigns.getValue();
            Iterator signs = lhpSigns.entrySet().iterator();
            while (signs.hasNext()) {
                Map.Entry sign = (Map.Entry) signs.next();
                Map signInfo = (Map) sign.getValue();
                Map<String, String> poi = new HashMap<String,String>();
                poi.put("pageNum", signInfo.get("pageNum").toString());
                poi.put("top", signInfo.get("top").toString());
                poi.put("left", signInfo.get("left").toString());
                poi.put("width", signInfo.get("width").toString());
                poi.put("height", signInfo.get("height").toString());
                poi.put("sealUrl", signInfo.get("sealUrl").toString());
                list.add(poi);
            }
        }

        if(Empty.isNull(pdfPath)) return JsonData.Error("参数不能为空");
        pdfPath = path + pdfPath.replace("./", "");
        newPDFPath = newPath + newPDFPath.replace("./", "");
        try {
            Pdf.generatePDF(pdfPath, newPDFPath, pdfHeight, pdfWidth, list, pwd, seal);
            return JsonData.success("处理成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JsonData.Error("处理失败");
        }
    }
}
